<?php

namespace app\admin\controller;

use app\admin\controller\AdminBaseController;
use app\model\device\DeviceBrandModel;
use app\model\device\DeviceClassModel;
use app\model\device\DeviceTypeModel;
use ExAdmin\ui\component\form\Form;
use ExAdmin\ui\component\grid\grid\Actions;
use ExAdmin\ui\component\grid\grid\Grid;
use think\Model;

class DeviceClassController extends AdminBaseController
{

    /**
     * @inheritDoc
     */
    protected function modelSet(): Model
    {
        return new DeviceClassModel();
    }

    public function index(): Grid
    {
        // 列表回调函数
        $callFunction = function (Grid $grid) {
            $this->hideGridItems($grid);
            $grid->model()->with(['device_type', 'device_brand'])
                ->order(["id" => 'desc']);
            $grid->title("设备型号");
            $grid->column('name', '名称');
            $grid->column('device_type.name', '类型');
            $grid->column('device_brand.name', '品牌');
            $grid->column('create_time', '创建时间');
            $grid->setForm()->drawer($this->form())->width("50%");


            $grid->actions(function (Actions $action, $data) {
                $action->hideDel();
            });


        };
        return Grid::create($this->model, $callFunction);
    }

    public function form(): Form
    {
        $callFunction = function (Form $form) {
            // 第一行
            $form->row(function (Form $form) {
                // 第一列
                $form->column(function (Form $form) {
                    $form->text("name", "型号名称")
                        ->required();
                })->span(12);
                // 第二列
                $form->column(function (Form $form) {
                    $form->text("code", "型号编码")
                        ->ruleAlphaDash()
                        ->help('字母、数字和下划线_及破折号')
                        ->required();
                })->span(12);

            });

            // 第二行
            $form->row(function (Form $form) {
                // 第一列
                $modelDeviceBrand = new DeviceBrandModel();
                $deviceBrandOptions = $modelDeviceBrand->getIdNameKeyValueList()->data;
                $form->select('device_brand_id', '品牌')
                    ->options($deviceBrandOptions ?: [])->required()->span(12);
                // 第二列
                $modelDeviceType = new DeviceTypeModel();
                $deviceTypeOptions = $modelDeviceType->getIdNameKeyValueList()->data;
                $form->select('device_type_id', '类型')
                    ->options($deviceTypeOptions ?: [])->required()->span(12);
            });

            if (!$form->isEdit()) {
                $form->hidden("uuid")->value(uuidByComb());
            }

        };
        return Form::create($this->model, $callFunction);
    }

}